package com.sky.business.sys.controller;

import com.sky.business.sys.domain.SystemConfig;
import com.sky.business.sys.mqtt.listener.CMCCDispatcherCallbackListener;
import com.sky.business.sys.mqtt.listener.LocalReportingCallbackListener;
import com.sky.business.sys.param.SystemConfigParam;
import com.sky.business.sys.service.SystemConfigService;
import com.sky.business.sys.util.MQTTClientUtils;
import com.sky.common.api.Result;
import com.sky.common.utils.StringUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 系统配置模块
 */
@RestController
@RequestMapping("/systemConfig")
@Tag(name = "系统设置", description = "系统设置控制层")
@Validated
public class SystemConfigController {

    @Autowired
    private SystemConfigService systemConfigService;

    @Resource
    private CMCCDispatcherCallbackListener dispatcherCallbackListener;

    @Resource
    private LocalReportingCallbackListener localReportingCallbackListener;


    @Operation(summary = "获取系统配置信息")
    @GetMapping(value="/showConfig", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result<SystemConfig> showConfig(){
        SystemConfig config = systemConfigService.getSystemConfig();
        return Result.success(config);
    }

    @Operation(summary = "保存系统配置信息")
    @PostMapping(value = "/setConfig", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result<Object> setConfig(@RequestBody SystemConfigParam config){

        String certificatePath = config.getCertificatePath();
        //证书目录未配置表示不使用加密接口
        if(StringUtils.isNotEmpty(certificatePath)) {
            Path caPath = Paths.get(certificatePath, "ca.pem");
            Path certPath = Paths.get(certificatePath, "cert.pem");
            Path keyPath = Paths.get(certificatePath, "key.pem");

            if (!Files.isDirectory(Paths.get(certificatePath))) {
                return Result.failed("证书目录不存在");
            }
            if (!Files.exists(caPath) ||
                    !Files.exists(certPath) ||
                    !Files.exists(keyPath)) {
                return Result.failed("证书文件不存在");
            }
        }

        SystemConfig systemConfig = systemConfigService.getSystemConfig();

        systemConfig.setEdgeName(config.getEdgeName());
        systemConfig.setEdgeIp(config.getEdgeIp());
        
        systemConfig.setCmccMQTTServiceHost(config.getCmccMQTTServiceHost());
        systemConfig.setCmccMQTTServicePort(config.getCmccMQTTServicePort());
        systemConfig.setCmccMQTTServiceUsername(config.getCmccMQTTServiceUsername());
        systemConfig.setCmccMQTTServicePassword(config.getCmccMQTTServicePassword());
        systemConfig.setCmccDispatcherTopic(config.getCmccDispatcherTopic());
        systemConfig.setCmccReportingTopic(config.getCmccReportingTopic());
        systemConfig.setCmccMQTTClientId(config.getCmccMQTTClientId());

        systemConfig.setLocalMQTTServiceHost(config.getLocalMQTTServiceHost());
        systemConfig.setLocalMQTTServicePort(config.getLocalMQTTServicePort());
        systemConfig.setLocalMQTTServiceUsername(config.getLocalMQTTServiceUsername());
        systemConfig.setLocalMQTTServicePassword(config.getLocalMQTTServicePassword());
        systemConfig.setLocalReportingTopic(config.getLocalReportingTopic());
        systemConfig.setLocalMQTTClientId(config.getLocalMQTTClientId());

        systemConfig.setControlServiceHost(config.getControlServiceHost());
        systemConfig.setControlServicePort(config.getControlServicePort());

        systemConfig.setHorizontalMoveThreshold(config.getHorizontalMoveThreshold());
        systemConfig.setVerticalMoveThreshold(config.getVerticalMoveThreshold());
        systemConfig.setObjWidth(config.getObjWidth());
        systemConfig.setObjHeight(config.getObjHeight());
        systemConfig.setRatio(config.getRatio());
        systemConfig.setMinZoomRatio(config.getMinZoomRatio());
        systemConfig.setMaxZoomRatio(config.getMaxZoomRatio());
        systemConfig.setMinZoomDistance(config.getMinZoomDistance());

        systemConfig.setCertificatePath(certificatePath);

        systemConfigService.saveOrUpdate(systemConfig);

        // 移动和本地的任务下发和心跳上报的Topic保存在工具类的静态属性中
        MQTTClientUtils.CMCC_DISPATCHER_TOPIC = systemConfig.getCmccDispatcherTopic();
        MQTTClientUtils.CMCC_REPORTING_TOPIC = systemConfig.getCmccReportingTopic();
        MQTTClientUtils.LOCAL_REPORTING_TOPIC = systemConfig.getLocalReportingTopic();

        try {
            // 销毁当前MQTT连接
            MQTTClientUtils.disconnect(MQTTClientUtils.LOCAL_MQTT_CLIENT);
            MQTTClientUtils.disconnect(MQTTClientUtils.CMCC_MQTT_CLIENT);

            // 构造MQTT连接参数
            MqttConnectOptions cmccOptions = MQTTClientUtils.createOptions(systemConfig.getCmccMQTTServiceUsername(), systemConfig.getCmccMQTTServicePassword());
            MqttConnectOptions localOptions = MQTTClientUtils.createOptions(systemConfig.getLocalMQTTServiceUsername(), systemConfig.getLocalMQTTServicePassword());

            // 重新创建移动MQTT服务的Client 移动的client订阅移动任务下发的Topic
            MQTTClientUtils.createCMCCMQTTClient(systemConfig.getCmccMQTTServiceHost(), systemConfig.getCmccMQTTServicePort(), systemConfig.getCmccMQTTClientId(), cmccOptions,dispatcherCallbackListener);

            // 重新创建本地MQTT服务的Client 本地client订阅本地心跳上报的Topic
            MQTTClientUtils.createLocalMQTTClient(systemConfig.getLocalMQTTServiceHost(), systemConfig.getLocalMQTTServicePort(), systemConfig.getLocalMQTTClientId(), localOptions,localReportingCallbackListener);

        } catch (MqttException e) {
            return Result.failed("保存成功，但连接MQTT服务器异常，请检查");
        }
        return Result.success();
    }


    public static void main(String[] args) {
        String certificatePath = "C:\\Users\\fxw11\\Desktop\\certificate";
        Path caPath = Paths.get(certificatePath, "ca.pem");
        Path certPath = Paths.get(certificatePath, "cert.pem");
        Path keyPath = Paths.get(certificatePath, "key.pem");
        if (!Files.isDirectory(Paths.get(certificatePath)) ||
                !Files.exists(caPath) ||
                !Files.exists(certPath) ||
                !Files.exists(keyPath)) {
            System.out.println("不存在");
        }else{
            System.out.println("存在");
        }

    }

}
